package Back;

import Back.MAP;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

public class ReplayPanel extends JPanel {
    private MAP mapData;
    private int relativeTime = 0; // UI 使用的相对时间（从 0 开始）
    private Timer timer;
    private JSlider progressSlider;
    private JLabel timeLabel;

    // 地图面板（用于绘制地图）
    private JPanel mapPanel;

    public ReplayPanel(MAP mapData) {
        this.mapData = mapData;
        this.mapData.initializeCarPositions();
        this.mapData.initemaplight();
        initializeUI();
    }

    private void initializeUI() {
        // 设置为绝对布局
        setLayout(null);

        // 创建地图面板
        mapPanel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                drawMap(g);
            }
        };
        mapPanel.setLayout(null);
        mapPanel.setBackground(Color.WHITE);

        // 设置地图面板位置和大小
        mapPanel.setBounds(40, 40, 1000, 600);

        // 控制面板
        JPanel controlPanel = new JPanel();
        controlPanel.setLayout(null); // 绝对布局
        controlPanel.setBounds(20, 630, 800, 150); // x, y, width, height

        // 进度条
        int maxRelativeTime = mapData.max_time - mapData.min_time;
        progressSlider = new JSlider(0, maxRelativeTime, 0);
        progressSlider.setMajorTickSpacing(maxRelativeTime / 10);
        progressSlider.setPaintTicks(true);
        progressSlider.setBounds(10, 10, 780, 40);
        progressSlider.addChangeListener(e -> {
            if (!progressSlider.getValueIsAdjusting()) {
                setTime(progressSlider.getValue());
                mapPanel.repaint();
            }
        });

        // 时间标签
        timeLabel = new JLabel("时间: 0/" + maxRelativeTime);
        timeLabel.setBounds(350, 60, 150, 20);

        // 按钮面板
        JButton playButton = new JButton("播放");
        JButton pauseButton = new JButton("暂停");
        JButton restartButton = new JButton("重新开始");
        JButton fastForwardButton = new JButton("快进");
        JButton slowMotionButton = new JButton("慢放");

        playButton.setBounds(100, 90, 100, 30);
        pauseButton.setBounds(210, 90, 100, 30);
        restartButton.setBounds(320, 90, 120, 30);
        fastForwardButton.setBounds(450, 90, 100, 30);
        slowMotionButton.setBounds(560, 90, 100, 30);

        playButton.addActionListener(e -> startPlayback());
        pauseButton.addActionListener(e -> pausePlayback());
        restartButton.addActionListener(e -> restartPlayback());
        fastForwardButton.addActionListener(e -> setPlaybackSpeed(2.0));
        slowMotionButton.addActionListener(e -> setPlaybackSpeed(0.5));

        // 添加按钮到控制面板
        controlPanel.add(timeLabel);
        controlPanel.add(progressSlider);
        controlPanel.add(playButton);
        controlPanel.add(pauseButton);
        controlPanel.add(restartButton);
        controlPanel.add(fastForwardButton);
        controlPanel.add(slowMotionButton);

        // 添加主组件
        add(mapPanel);
        add(controlPanel);

        // 初始化定时器
        timer = new Timer(100, e -> {
            if (relativeTime < maxRelativeTime) {
                setTime(relativeTime + 1);
                mapPanel.repaint();
            } else {
                pausePlayback();
            }
        });
    }

    private void drawMap(Graphics g) {
        if (mapData == null) return;

        int absoluteTime = mapData.min_time + relativeTime;

        // 获取当前绘图区域大小（即 mapPanel 的实际宽度和高度）
        int panelWidth = mapPanel.getWidth();
        int panelHeight = mapPanel.getHeight();

        // 计算可用空间（留出边距）
        int margin = 0;
        int usableWidth = panelWidth - margin * 2;
        int usableHeight = panelHeight - margin * 2;

        // 动态计算每个单元格的大小
        int cellWidth = usableWidth / mapData.width;
        int cellHeight = usableHeight / mapData.height;
        int cellSize = Math.min(cellWidth, cellHeight);

        int width = mapData.width;
        int height = mapData.height;

        // 更新小车位置并点亮九宫格
        for (int carId = 1; carId <= mapData.carcount; carId++) {
            Point carPos = getCarPosition(carId, relativeTime);
            if (carPos != null) {
                mapData.lightarea(carPos.x, carPos.y);
            }
        }

        // 获取当前时间点的点亮状态
        String lightState = mapData.maplighstate.get(relativeTime);

        // 绘制地图
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                int index = y * width + x;
                int screenX = x * cellSize + margin;
                int screenY = y * cellSize + margin;

                // 检查是否被点亮
                if (lightState.charAt(index) == '1') {
                    // 检查是否是小车位置
                    boolean isCar = false;
                    int carId = -1;

                    for (int i = 1; i <= mapData.carcount; i++) {
                        Point carPos = mapData.getCarPosition(i, relativeTime);
                        if (carPos != null && carPos.x == x && carPos.y == y) {
                            isCar = true;
                            carId = i;
                            break;
                        }
                    }

                    if (isCar) {
                        // 绘制小车
                        g.setColor(Color.BLUE);
                        g.fillOval(screenX, screenY, cellSize, cellSize);
                        g.setColor(Color.YELLOW);
                        g.drawString(String.valueOf(carId),
                                screenX + cellSize / 2 - 5,
                                screenY + cellSize / 2 + 5);
                    }
                    // 检查是否是障碍物
                    else if (mapData.map_obstacle[y][x] == 1) {
                        g.setColor(Color.RED);
                        g.fillRect(screenX, screenY, cellSize, cellSize);
                    }
                    // 普通点亮区域
                    else {
                        g.setColor(Color.LIGHT_GRAY);
                        g.fillRect(screenX, screenY, cellSize, cellSize);
                    }

                    // 绘制网格边框
                    g.setColor(Color.DARK_GRAY);
                    g.drawRect(screenX, screenY, cellSize, cellSize);
                }
                // 未点亮区域
                else {
                    g.setColor(Color.BLACK);
                    g.fillRect(screenX, screenY, cellSize, cellSize);
                }
            }
        }
    }

    private Point getCarPosition(int carId, int time) {
        if (carId < 1 || carId > mapData.carcount) return null;
        if (time < 0 || time >= mapData.maplighstate.size()) return null;

        return mapData.carPositions[carId].get(time);
    }

    public void setTime(int relativeTime) {
        int maxRelativeTime = mapData.max_time - mapData.min_time;
        if (relativeTime < 0) relativeTime = 0;
        if (relativeTime > maxRelativeTime) relativeTime = maxRelativeTime;

        this.relativeTime = relativeTime;
        progressSlider.setValue(relativeTime);
        timeLabel.setText("时间: " + relativeTime + "/" + maxRelativeTime);
    }

    public void startPlayback() {
        timer.start();
    }

    public void pausePlayback() {
        timer.stop();
    }

    public void restartPlayback() {
        setTime(0);
    }

    public void setPlaybackSpeed(double speedFactor) {
        timer.setDelay((int)(100 / speedFactor));
    }
}
